package com.icode.web.controller.User;

import com.icode.core.dto.user.MemberDTO;
import com.icode.core.shared.DataToJson;
import com.icode.service.user.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: xianfei
 * Date: 15-3-16
 * Time: 上午10:54
 * To change this template use File | Settings | File Templates.
 */
@Controller("memberController")
@RequestMapping(value = "/member")
    public class MemberController {

    @Autowired
    private MemberService memberService;

    @RequestMapping(value = "show/{guid}", method = RequestMethod.GET)
    public ModelAndView showMember(@PathVariable String guid) {
        MemberDTO memberDTO = memberService.findMemberByGuid(guid);
        if ("1".equals(guid) || memberDTO == null) {
            return new ModelAndView("back/member/memberOverView", "memberDTO", new MemberDTO());
        }
        return new ModelAndView("back/member/memberOverView", "memberDTO", memberDTO);
    }

    @RequestMapping(value = "listByMore")
    public void listByMore(String name, String idCard, String phoneNum, HttpServletResponse response) {
        List<MemberDTO> memberDTOs = memberService.findMemberByMore(name, idCard, phoneNum);
        DataToJson.memberDataToJson(memberDTOs, response);
    }

    @RequestMapping(value = "list", method = RequestMethod.GET)
    public ModelAndView list() {
        List<MemberDTO> memberDTOs = memberService.findAllMember();
        return new ModelAndView("back/member/member", "memberDTOs", memberDTOs);
    }

    @RequestMapping(value = "save", method = RequestMethod.POST)
    public String saveOrUpdateMember(@ModelAttribute(value = "memberDTO") @Valid MemberDTO memberDTO,BindingResult bindingResult) {
        if(bindingResult.hasErrors()){
            return "back/member/memberOverView";
        }
        memberService.saveOrUpdateMember(memberDTO);
        return "redirect:/member/list";
    }

    @RequestMapping(value = "delete/{guid}", method = RequestMethod.GET)
    public String deleteMember(@PathVariable String guid) {
        memberService.deleteMemberByGuid(guid);
        return "redirect:/member/list";
    }

}
